import os
import time

from utils import doc_util, read_config, date_util, json_util


class EventContext:
    def __init__(self):
        self.key = ''
        self.info = ''
        self.update_count = 500  # 多少次记录
        self.count = 0
        self.expire = 10
        self.expire_time = None #


# expire 分钟
def record_expire(key, info, expire):
    timestamp_now = date_util.get_timestamp_now()
    event_list = fresh()
    event_list.append({'key': key, 'expire': timestamp_now + expire * 60, 'info': info})
    doc_util.gen_new_doc(os.path.join(read_config.data_path, 'utils', 'event'), 'event', event_list)


def record_date(key, info, date: str):
    record_expire(key, info, int((date_util.time_to_timestamp(date) - date_util.get_timestamp_now()) / 60))


def has_record(key) -> bool:
    event_list = fresh()
    for event_info in event_list:
        if event_info.get('key') == key:
            return True
    return False


def get_record(key):
    event_list = fresh()
    for event_info in event_list:
        if event_info.get('key') == key:
            return event_info.get('info')
    return None


def update_record(key, info):
    event_list = doc_util.get_doc_info_null(os.path.join(read_config.data_path, 'utils', 'event', 'event'))
    for event_info in event_list:
        event_info = json_util.to_json(event_info)
        if event_info.get('key') == key:
            event_info['info'] = info
    doc_util.gen_new_doc(os.path.join(read_config.data_path, 'utils', 'event'), 'event', event_list)


def del_record(key):
    event_list = doc_util.get_doc_info_null(os.path.join(read_config.data_path, 'utils', 'event', 'event'))
    event_list_new = []
    for event_info in event_list:
        event_info = json_util.to_json(event_info)
        if event_info.get('key') == key:
            continue
        event_list_new.append(event_list_new)
    doc_util.gen_new_doc(os.path.join(read_config.data_path, 'utils', 'event'), 'event', event_list_new)


def fresh():
    timestamp_now = date_util.get_timestamp_now()
    event_list = doc_util.get_doc_info_null(os.path.join(read_config.data_path, 'utils', 'event', 'event'))
    event_list_new = []
    for event_info in event_list:
        event_info = json_util.to_json(event_info)
        if timestamp_now > int(event_info.get('expire')):
            continue
        event_list_new.append(event_info)
    return event_list_new


if __name__ == '__main__':
    print(int(round(time.time())))
    record_date(1, 'abdcd', '2021-12-14 00:00:00')
    record_date(2, 'abdcf', '2021-12-14 01:00:00')
